package io.codescience.aianaly.utils;

import io.codescience.aianaly.model.User;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class AuthUtil {

    private static JwtUtil jwtUtil;

    // 设置JwtUtil实例（可以通过@PostConstruct或配置类设置）
    public static void setJwtUtil(JwtUtil jwtUtilInstance) {
        jwtUtil = jwtUtilInstance;
    }

    // 检查用户是否登录
    public static boolean isLoggedIn(HttpSession session) {
        return session.getAttribute("user") != null;
    }

    // 从请求中检查JWT token
    public static boolean isLoggedIn(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            String token = Arrays.stream(cookies)
                    .filter(cookie -> "jwtToken".equals(cookie.getName()))
                    .map(Cookie::getValue)
                    .findFirst()
                    .orElse(null);

            return token != null && jwtUtil != null && jwtUtil.isTokenValid(token) && !jwtUtil.isTokenExpired(token);
        }
        return false;
    }

    // 检查用户是否为管理员
    public static boolean isAdmin(HttpSession session) {
        User user = (User) session.getAttribute("user");
        return user != null && user.isAdmin();
    }

    // 获取当前登录用户
    public static User getCurrentUser(HttpSession session) {
        return (User) session.getAttribute("user");
    }

    // 检查权限并重定向
    public static String checkAdminAndRedirect(HttpSession session) {
        if (!isLoggedIn(session)) {
            return "redirect:/login";
        }
        if (!isAdmin(session)) {
            String encodedMessage = URLEncoder.encode("权限不足", StandardCharsets.UTF_8);
            return "redirect:/interview?error=" + encodedMessage;
        }
        return null;
    }
}